import { logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { getRouter, login } from '@/views/login/api/login'
import router from '@/router'
import { Message } from 'element-ui'
import { getUserInfo, removeUserInfo, setUserInfo } from '@/utils/userinfo'
import { setUserRouter, removeUserRouter, getUserRouter } from '@/utils/userRouter'
const getDefaultState = () => {
  return {
    token: getToken(),
    user: getUserInfo()
  }
}

const state = getDefaultState()

const getters = {
  userInfo(state) {
    return getUserInfo()
  },
  userRouter(state) {
    return getUserRouter()
  }
}
const mutations = {
  // 退出登陆
  logout(state) {
    state.token = ''
    state.user = {}
    removeToken()
    removeUserInfo()
    removeUserRouter()
    router.push('/login')
  },
  // 存储用户信息
  saveUserInfo(state, val) {
    state.token = val.token.token
    state.user = val.user
  }
}

const actions = {
  // user login
  async login(context, data) {
    const res = await login(data)
    setToken(res.data.token.token)
    setUserInfo(res.data.user)
    context.commit('saveUserInfo', res.data)
    router.push('/')
    Message.success('登录成功')
  },

  async getUserRouter() {
    const res = await getRouter()
    setUserRouter(res.data)
  }
  // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const { data } = response

  //       if (!data) {
  //         return reject('Verification failed, please Login again.')
  //       }

  //       const { name, avatar } = data

  //       commit('SET_NAME', name)
  //       commit('SET_AVATAR', avatar)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // // user logout
  // logout({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     logout(state.token).then(() => {
  //       removeToken() // must remove  token  first
  //       resetRouter()
  //       commit('RESET_STATE')
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // // remove token
  // resetToken({ commit }) {
  //   return new Promise(resolve => {
  //     removeToken() // must remove  token  first
  //     commit('RESET_STATE')
  //     resolve()
  //   })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

